<template>
  <div>
    <div class="header flex items-center justify-around">
      <div class="flex items-center">
        <img class="block w-[230px]" alt="Vue logo" src="~@/assets/logo1.png" />
        <span class="text-[24px] ml-[5px]"> | 统一身份认证平台</span>
      </div>
      <img
        class="block w-[230px] opacity-50"
        alt="Vue logo"
        src="~@/assets/foot-logo.png"
      />
    </div>
    <div class="main">
      <div class="login w-[264px]">
        <div class="top flex">
          <div
            class="type"
            :class="activeID === 1 ? 'login-type-active' : 'login-type'"
            @click="activeID = 1"
          >
            账号登录
          </div>
          <div
            class="type"
            :class="activeID === 2 ? 'login-type-active' : 'login-type'"
            @click="activeID = 2"
          >
            二维码登录
          </div>
        </div>
        <div class="form p-[20px]">
          <el-form
            ref="ruleFormRef"
            :model="formData"
            :rules="rules"
            class="login-right-bottom-formbox-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入您的账号"
                size="large"
                clearable
                :prefix-icon="User"
                @keyup.enter="handleLogin(ruleFormRef)"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                placeholder="请输入您的密码"
                size="large"
                show-password
                clearable
                :prefix-icon="Lock"
                @keyup.enter="handleLogin(ruleFormRef)"
              />
            </el-form-item>
            <el-form-item v-if="showCode" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="算术答案"
                size="large"
                clearable
                style="width: 130px"
                @keyup.enter="handleLogin(ruleFormRef)"
              />
              <img
                :src="codeImg"
                alt="刷新验证码"
                class="w-[85px] ml-[5px] cursor-pointer"
                @click="toCaptchaImage"
              />
            </el-form-item>
          </el-form>
          <div class="flex justify-between mt-[20px]">
            <el-button class="btn1" @click="handleLogin(ruleFormRef)"
              >登录
            </el-button>
            <el-button class="btn2" @click="reset"> 重置</el-button>
          </div>
          <div class="flex justify-between mt-[20px] items-center">
            <el-checkbox
              v-model="isRemember"
              label="记住密码"
              size="small"
              @change="clickCheck"
            />
            <div class="more">
              <el-link href="" target="" class="mr-[5px] more">常见问题</el-link
              >|
              <el-link href="" target="" class="more">忘记密码</el-link>
            </div>
          </div>
          <div class="text-[12px] flex justify-center items-center mt-[20px]">
            <van-icon
              name="graphic"
              size="20"
              color="#52d7ab"
              class="mr-[5px]"
            />手机号登录
          </div>
        </div>
      </div>
    </div>
    <div class="footer flex justify-center items-center">
      版权所有Copyright©荆楚理工学院 地址:湖北荆门市象山大道33号
    </div>
  </div>
</template>
<script setup lang="ts">
import { login, captchaImage } from "@/api";
import { ref, onMounted } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import type { FormInstance, FormRules, ElMessage } from "element-plus";
import { setToken } from "@/utils/auth";
import { useRouter } from "vue-router";
const router = useRouter();
interface RuleForm {
  username: string;
  password: string;
  code?: string;
  uuid?: string;
}

const ruleFormRef = ref<FormInstance>();
const formData = ref<RuleForm>({
  username: "",
  password: "",
  code: "",
  uuid: ""
});
let activeID = ref(1);

const reset = () => {
  formData.value = {
    username: "",
    password: "",
    code: ""
  };
};
const rules = ref({
  username: [
    { required: true, message: "请输入您的账号", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入您的密码", trigger: "blur" },
    { min: 8, max: 20, message: "长度在 8 到 20 个字符", trigger: "blur" }
  ]
});
const toLogin = params => {
  login(params).then(res => {
    console.log(res);
    if (res.code === 200) {
      // 记住密码
      if (isRemember.value) {
        localStorage.setItem(
          "loginInfo",
          JSON.stringify({
            username: params.username,
            password: params.password
          })
        );
        // 不记住密码
      } else {
        localStorage.removeItem("loginInfo");
      }
      setToken(res.token);
      setTimeout(() => {
        router.push("/safeCenter");
      }, 300);
    } else {
      if (res.code === 50002) {
        showCode.value = true;
        toCaptchaImage();
      }
      ElMessage.error(res.msg);
    }
  });
};
const toCaptchaImage = () => {
  captchaImage().then(res => {
    console.log(res);
    if (res.code === 200) {
      uuid.value = res.uuid;
      codeImg.value = "data:image/png;base64," + res.img;
    } else {
      // ElMessage.error(res.msg);
    }
  });
};
let showCode = ref(false);
let uuid = ref("");
let codeImg = ref("");
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const params = { ...formData.value };
      if (showCode.value) {
        params.uuid = uuid.value;
      }
      toLogin(params);
    } else {
      // ElMessage.error("修改失败，请重试");
    }
  });
};
const isRemember = ref(false);
const clickCheck = () => {
  console.log(isRemember.value);
};
onMounted(() => {
  // 判断已记住密码逻辑
  const loginInfo = localStorage.getItem("loginInfo");
  if (loginInfo) {
    const { username, password } = JSON.parse(loginInfo);
    formData.value.username = username;
    formData.value.password = password;
    isRemember.value = true;
  }
});
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  height: 80px;
  color: var(--color-header-text);
  background: var(--color-header-background-1);
}
.main {
  height: calc(100vh - 80px - 40px);
  background: url("@/assets/login-bg.jpg") no-repeat center;
  background-size: 100% 100%;
  .login {
    position: fixed;
    top: 25%;
    right: 10%;
    border-radius: 8px;
    background-color: var(--color-main-background-secondary);
    box-shadow: 0px 5px 10px 5px rgba(var(--color-header-background-1), 0.25);
    .type {
      padding: 8px 30px;
      &:first-child {
        border-top-left-radius: 8px;
      }
      &:last-child {
        border-top-right-radius: 8px;
      }
    }
    .login-type {
      color: var(--color-header-text);
      background: var(--color-header-background-1);
      &:hover {
        cursor: pointer;
      }
    }
    .login-type-active {
      color: var(--color-header-background-1);
      background: var(--color-header-text);
      cursor: default;
    }
  }
}
.footer {
  width: 100%;
  height: 40px;
  color: var(--color-header-text);
  background: var(--color-header-background-1);
}
.el-button {
  padding: 8px 30px;
  color: var(--color-header-text);
}
.btn1 {
  background: var(--color-header-background-1);
}
.btn2 {
  background: #99a29f;
}
.more {
  color: #73665b;
  font-size: 12px;
}
</style>
